﻿// Base container type
define([
    'Wjs/ui/elements/Element'
],
function () {
    'use strict';

    return Wjs.defineOnce({

        type: 'Container',

        setDefaultItemType: function (type) {

            this.defaultItemType = type;

            return this;
        },

        setTemplate: function (template) {

            this.template = Wjs.compile(template); // Compile the template if any was provided

            return this;
        },

        onItemAdded: function (fcn) {

            this.itemAddedHandler = fcn;

            return this;
        },

        onItemsRendered: function (fcn) {

            this.itemsRenderedHandler = fcn;

            return this;
        },

        onItemRemoved: function (fcn) {

            this.itemRemovedHandler = fcn;

            return this;
        },

        onItemsCleared: function (fcn) {

            this.itemsClearedHandler = fcn;

            return this;
        },

        createItem: function (item, type) {

            if (!item) {

                throw 'item is required';
            }

            type = item.type || type || this.defaultItemType;

            if (item instanceof (Wjs.getType('Element'))) // The item is already created
            {
                return item;
            }

            if (type && Wjs.isFunction(type)) { // If the type is a function, then get the type by calling it

                type = type.call(this, item);
            }

            if (!type) { // The type was not provided, throw an error

                throw 'Type is required to create item';
            }

            return Wjs.create(item, type, this);
        },

        handleItemAdded: function (item) {

            if (this.isRendered && this.isRendered()) { // Append it to the DOM as well

                item.render();
            }

            if (this.itemAddedHandler) {

                this.itemAddedHandler(item);
            }
        },

       
        setMask: function (mask) {

            if (!this.isRendered) {

                return;
            }

            if (this.mask) {

                this.mask.destroy();
            }

            this.mask = this.createItem(mask, 'Mask');

            this.mask.setParent(this);

            if (this.isRendered()) {

                this.mask.render();
            }

            return this;
        },

        getMask: function () {

            return this.mask;
        }

    });
});